<template>
  <div>
    <el-dialog
      title="用户注册"
      :visible.sync="centerDialogVisible"
      width="500px"
      center
    >
      <!-- form表单 -->
      <el-form
        :model="ruleForm"
        ref="submitForm"
        :rules="rules"
        label-width="70px"
        label-position="left"
      >
        <!-- 头像 -->
        <!--
          action:必选参数，上传的地址
          data:上传时附带的额外参数
         -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="uploadMoreParams"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            style=" width:350px"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- 昵称 -->
        <el-form-item label="账号" prop="username" style="width:50%">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email" style="width:50%">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="phone" style="width:50%">
          <el-input v-model.number="ruleForm.phone"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password" style="width:50%">
          <el-input v-model="ruleForm.password" show-password></el-input>
        </el-form-item>
        <!-- 图形码 -->
        <el-row>
          <!-- 图形码文本框 -->
          <el-col :span="13">
            <el-form-item label="图形码" prop="praphCode" style="width:80%">
              <el-input v-model="ruleForm.praphCode"></el-input> </el-form-item
          ></el-col>
          <!-- 图形码图片 -->
          <el-col :span="10"
            ><img
              :src="codeUrl"
              alt=""
              style="width:126px;height:40px;margin-left:-80px"
              @click="changeCodeUrl"
          /></el-col>
        </el-row>
        <!-- 验证码 -->
        <el-row>
          <el-col :span="13">
            <el-form-item label="验证码" prop="captcha" style="width:80%">
              <el-input v-model="ruleForm.captcha"></el-input> </el-form-item
          ></el-col>
          <el-col :span="11"
            ><el-button
              style="height:40px;margin-left:-80px"
              @click="getCaptcha"
              >获取用户验证码</el-button
            ></el-col
          >
        </el-row>
      </el-form>
      <!-- 按钮功能 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn">取 消</el-button>
        <el-button type="primary" @click="registerBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      centerDialogVisible: false, // 决定注册窗口显示
      // 图形码url地址
      codeUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      imageUrl: '', // 预览的图片地址
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', // 上传头像地址
      uploadMoreParams: { image: null }, // 上传时的额外参数
      // 模型
      ruleForm: {
        avatar: '', // 头像
        username: '', // 昵称
        email: '', // 邮箱
        phone: '', // 手机号
        password: '', // 密码
        praphCode: '', // 图形码
        captcha: '' // 验证码
      },
      // 规矩验证
      rules: {
        // 头像
        avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        // 昵称
        username: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('昵称不能为空'))
                return
              }
              const reg = /^[a-z]{1}[a-zA-Z0-9_-]{5,11}$/
              if (!reg.test(value)) {
                return callback(new Error('小写字母开头，6-12位'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        // 邮箱
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('邮箱不能为空'))
                return
              }
              // eslint-disable-next-line
              const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
              if (!reg.test(value)) {
                return callback(new Error('邮箱格式不正确'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        // 手机
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('手机号码不能为空'))
                return
              }
              // 正则匹配
              const reg = /^1[3-9]\d{9}$/
              if (!reg.test(value)) {
                return callback(new Error('手机格式不正确'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        // 密码
        password: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('密码不能为空'))
                return
              }
              // 正则匹配
              const reg = /^[a-z]{1}[a-zA-Z0-9_-]{5,15}$/
              if (!reg.test(value)) {
                return callback(new Error('小写字母开头,6-16位'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        // 图形码
        praphCode: [
          {
            required: true,
            min: 4,
            max: 4,
            message: '图形码不正确',
            trigger: 'blur'
          }
        ],
        // 验证码
        captcha: [{ required: true, message: '验证码错误', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 重新获取图形码
    changeCodeUrl () {
      this.codeUrl = `${
        process.env.VUE_APP_BASEURL
      }/captcha?type=sendsms&t=${new Date() - 0}`
    },
    // 获取手机验证码
    async getCaptcha () {
      let count = 0
      this.$refs.submitForm.validateField(
        ['phone', 'praphCode'],
        errorMessage => {
          if (!errorMessage) {
            count++
          }
        }
      )
      if (count === 2) {
        // await 请求
        const res = await this.$axios.post('/sendsms', {
          // 双向绑定的属性
          phone: this.ruleForm.phone,
          code: this.ruleForm.praphCode
        })
        if (res.code === 200) {
          // 把请求到的验证码赋值给文本框
          this.ruleForm.captcha = res.data.captcha
        } else {
          // 弹出错误信息
          this.$message.error(res.message)
          // 刷新图形码
          this.changeCodeUrl()
        }
      }
    },
    // 上传头像上传成功之后
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res)
      if (res.code === 200) {
        this.ruleForm.avatar = res.data.file_path
      }
    },
    // 上传头像之前
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG png gif格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.uploadMoreParams.image = file
      return isImage && isLt2M
    },
    // 用户注册
    registerBtn () {
      this.$refs.submitForm.validate(async valid => {
        if (!valid) return

        const res = await this.$axios.post('/register', this.ruleForm)
        // console.log(res)
        if (res.code === 200) {
          this.$message.success('注册成功')
          // 关闭注册窗口
          this.centerDialogVisible = false
        } else {
          this.$message.error(res.message)
          // 刷新图形码
          this.changeCodeUrl()
        }
      })
    },
    // 取消按钮
    cancelBtn () {
      this.centerDialogVisible = false
    }
  },
  watch: {
    // 监听注册页面窗口是否关闭
    centerDialogVisible (isClose) {
      // console.log(isClose)
      if (!isClose) {
        // 清空form表单文本值
        this.$refs.submitForm.resetFields()
        // 清空预览的图片
        this.imageUrl = ''
      }
    }
  }
}
</script>

<style lang="less">
.el-dialog__header {
  background-color: #0f9efa;
  .el-dialog__title {
    color: #fff;
  }
  .el-dialog__headerbtn {
    .el-dialog__close {
      color: #fff !important;
    }
  }
}
// 以下是上传头像的样式
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
